function doInitWin() {
	dhxWins = new dhtmlXWindows();
	dhxWins.enableAutoViewport(true);
	dhxWins.setImagePath("scripts/dhtmlxwindows-codebase/imgs/");
}

function initPage() {

	$('mCHCIDrow').hide();
	$('mTTIDrow').hide();

	loadTissues();
}

function loadTissues() {
	new Ajax.Request('mainServlet', {
		method : 'POST',
		parameters : {
			appAction : 'ajaxLoadTissueList'
		},
		onFailure : function(transport) {
			handleErrorResponseWindow(transport.responseText); // cf. common.js
		},
		onSuccess : function(transport) {
			var jsonResponse = transport.responseText;
			existingTissuesList = jsonResponse.evalJSON();
		}
	});

	loadTissueTypes();

	initTissueTypesGrid();
	fillTissueTypeGrid();
}

function initTissueTypesGrid() {
	tissueTypeGrid = new dhtmlXGridObject('tissueTypeGridContainer');
	tissueTypeGrid.setHeader("Tissue Type ID, Description, Occurrences");
	tissueTypeGrid.setColumnIds("tissueTypeID, tissueTypeDescription,nOccurrences");
	tissueTypeGrid.setInitWidths("100,250,100");
	tissueTypeGrid.setColSorting("str,str,int");

	commonGridInit(tissueTypeGrid);

	tissueTypeGrid.init();

}

function createNewTissueType() {

	var newTT = $('newTissueTypeID').getValue().trim().toUpperCase();
	var desc = $('newTissueTypeDescription').getValue().trim();
	if(newTT.trim().length < 1){
		alert('You cannot submit an empty tissue type ID !');
	}
	else if (existingTissueTypesList.indexOf(newTT) != -1) {
		alert('The new Tissue Type you submitted (' + newTT + ') already exists !');
	}
	else {
		var doContinue = confirm('You are about to create a new Tissue Type : ' + newTT
				+ ', proceed ?');
		if (doContinue) {
			new Ajax.Request('mainServlet', {
				method : 'POST',
				parameters : {
					appAction : 'ajaxCreateNewTissueType',
					newTissueTypeID : newTT,
					description : desc
				},
				onFailure : function(transport) {
					handleErrorResponseWindow(transport.responseText); // cf.
					// common.js
					
				},
				onSuccess : function(transport) {
					alert('New Tissue Type : ' + newTT + ' successfully created !');
					fillTissueTypeGrid();
				}
			});
		}
		else {
			return;
		}
	}

}

function fillTissueTypeGrid() {
	tissueTypeGrid.clearAll();
	new Ajax.Request('mainServlet', {
		method : 'POST',
		parameters : {
			appAction : 'ajaxLoadTissueTypesFull'
		},
		onFailure : function(transport) {
			handleErrorResponseWindow(transport.responseText); // cf. common.js
		},
		onSuccess : function(transport) {
			var xmlString = transport.responseText;
			tissueTypeGrid.parse(xmlString);
		}
	});
}

function loadTissueTypes() {
	new Ajax.Request('mainServlet', {
		method : 'POST',
		parameters : {
			appAction : 'ajaxLoadTissueTypes'
		},
		onFailure : function(transport) {
			handleErrorResponseWindow(transport.responseText); // cf. common.js
		},
		onSuccess : function(transport) {
			var jsonResponse = transport.responseText;
			existingTissueTypesList = jsonResponse.evalJSON();

			var tissueTypeOptionsString = "";
			for ( var i = 0; i < existingTissueTypesList.size(); i++) {
				tissueTypeOptionsString += '<option>';
				tissueTypeOptionsString += existingTissueTypesList[i];
				tissueTypeOptionsString += '</option>';
			}
			$('newTissueTissueTypeID').update(tissueTypeOptionsString);
			$('masterTissueTissueTissueTypeID').update(tissueTypeOptionsString);
			$('tissueToDeleteTypeID').update(tissueTypeOptionsString);
		}
	});
}

function checkMasterTissue() {
	if ($('hasMasterTissue').getValue() == 'YES') {
		$('mCHCIDrow').show();
		$('mTTIDrow').show();
		masterTissueDefined = true;
	}
	else {
		$('masterTissueCHCID').setValue('');
		$('masterTissueTissueTissueTypeID').setValue('');
		$('mCHCIDrow').hide();
		$('mTTIDrow').hide();
		masterTissueDefined = false;
	}
}

function submitTissue() {
	if ($('newTissueCHCID').getValue().trim() != ""
			&& $('newTissueTissueTypeID').getValue().trim() != "") {
		if (isNaN($('newTissueCHCID').getValue().trim())) {
			alert('The CHC ID you gave is not a valid number !');
		}
		else {
			var chcID = new Number($('newTissueCHCID').getValue().trim());
			var tissueTypeID = $('newTissueTissueTypeID').getValue();
			var newTissue = new Tissue({
				chcID : chcID,
				tissueTypeID : tissueTypeID
			});

			// check if this tissue exists already
			var exists = false;
			for ( var i = 0; i < existingTissuesList.size(); i++) {
				if (newTissue.equals(existingTissuesList[i])) {
					exists = true;
				}
			}
			if (exists) {
				alert('Tissue ' + newTissue.toString() + ' already exists in the database !');
			}
			else {

				// alert('dummy');
				// checking master tissue and saving with master Tissue
				if (masterTissueDefined) {
					var mCHCID = new Number($('masterTissueCHCID').getValue().trim());
					var mTissueTypeID = $('masterTissueTissueTissueTypeID').getValue();
					if (isNaN(mCHCID)) {
						alert('The CHC ID you gave for the master tissue is not a valid number !');
					}
					else {
						var mTissue = new Tissue({
							chcID : mCHCID,
							tissueTypeID : mTissueTypeID
						});
						exists = false;
						for ( var i = 0; i < existingTissuesList.size(); i++) {
							if (mTissue.equals(existingTissuesList[i])) {
								exists = true;
								mTissue = new Tissue(existingTissuesList[i]);
							}
						}
						if (!exists) {
							alert('The master tissue ' + mTissue.toString()
									+ ' doesn\'t exist in the database !');
						}
						else {
							if (mTissue.hasMasterTissue()) {

								var win = dhxWins.createWindow("err", 500, 300, 500, 250);
								dhxWins.window("err").setText("Error !");
								win.attachHTMLString('You cannot use the tissue '
										+ mTissue.toHref() + ' as a master tissue, '
										+ 'since it already has a master tissue ('
										+ mTissue.getMasterTissue().toHref()
										+ ').<br/>Perhaps you should use '
										+ mTissue.getMasterTissue().toHref()
										+ ' as master tissue instead.');
							}
							else {
								new Ajax.Request('mainServlet', {
									method : 'POST',
									parameters : {
										appAction : 'ajaxCreateNewTissueWithMaster',
										newTissueCHCID : String.interpret(newTissue.chcID),
										newTissueTissueTypeID : newTissue.tissueTypeID,
										masterTissueCHCID : String.interpret(mTissue.chcID),
										masterTissueTypeID : mTissue.tissueTypeID
									},
									onFailure : function(transport) {
										handleErrorResponseWindow(transport.responseText); // cf.
										// common.js
									},
									onSuccess : function(transport) {
										var win = dhxWins.createWindow("success", 500, 300, 500,
												250);
										dhxWins.window("success").setText("Success !");
										win.attachHTMLString('New Tissue : ' + newTissue.toHref()
												+ ' successfully created,'
												+ ' with master Tissue : ' + mTissue.toHref());
										updateLinkContainer(newTissue);
										loadTissues();

									}
								});
							}
						}

					}
				}
				// saving tissue without master tissue
				else {
					new Ajax.Request('mainServlet', {
						method : 'POST',
						parameters : {
							appAction : 'ajaxCreateNewTissueWithoutMaster',
							newTissueCHCID : String.interpret(newTissue.chcID),
							newTissueTissueTypeID : newTissue.tissueTypeID
						},
						onFailure : function(transport) {
							handleErrorResponseWindow(transport.responseText); // cf.
							// common.js
						},
						onSuccess : function(transport) {
							// alert('New Tissue : '+newTissue.toString()+'
							// successfully created !');
							var win = dhxWins.createWindow("success", 500, 300, 500, 250);
							dhxWins.window("success").setText("Success !");
							win.attachHTMLString('New Tissue : ' + newTissue.toHref()
									+ ' successfully created.');
							updateLinkContainer(newTissue);
							loadTissues();
						}
					});
				}

			}

		}
	}
	else {
		alert('You must give a CHC ID and a Tissue Type ID for the new Tissue !');
	}
}

function checkNewTissueType() {
	if ($('newTissueTissueTypeID').getValue() == '*NEW*') {
		$('newTTIDrow').show();
		newTissueTypeDefined = true;
	}
	else {
		$('newTTIDrow').hide();
		newTissueTypeDefined = false;
	}
}

function updateLinkContainer(tissue) {
	var linkString = tissue.toHref();
	$('linkContainer').update(linkString);
}

function deleteTissue() {
	var chcID = $('tissueToDeleteCHCID').getValue().trim();
	var tissueTypeID = $('tissueToDeleteTypeID').getValue();
	if (isNaN($('newTissueCHCID').getValue().trim())) {
		alert('The CHC ID of the tissue you want to delete is not a valid number !');
	}
	else {
		var tissueToDelete = new Tissue({
			chcID : chcID,
			tissueTypeID : tissueTypeID
		});
		var exists = false;
		for ( var i = 0; i < existingTissuesList.size(); i++) {
			if (tissueToDelete.equals(existingTissuesList[i])) {
				tissueToDelete = new Tissue(existingTissuesList[i]);
				exists = true;
			}
		}
		if (!exists) {
			alert('The tissue you want to delete doesn\'t exist !');
		}
		else {
			var fullTissue;
			// check if the tissue to delete has eavData associated
			new Ajax.Request('mainServlet', {
				method : 'POST',
				parameters : {
					appAction : 'ajaxLoadTissue',
					chcID : tissueToDelete.chcID,
					tissueTypeID : tissueToDelete.tissueTypeID
				},
				onFailure : function(transport) {
					handleErrorResponseWindow(transport.responseText); // cf.
					// common.js
				},
				onSuccess : function(transport) {
					fullTissue = (transport.responseText).evalJSON();
					currentFullTissue = fullTissue;
					var eavData = new Hash(fullTissue.eavData);
					var confirmMessage;
					if (eavData != null && eavData.size() > 0) {
						confirmMessage = 'The tissue you want to delete ('
								+ tissueToDelete.toString() + ') is associated with data ('
								+ eavData.size() + ' variables).';
						confirmMessage += '\nDeleting the tissue will erase all this information.'
								+ ' Do you want to proceed ?';
					}
					else {
						confirmMessage = 'Are you sure you want to delete this tissue : '
								+ tissueToDelete.toString() + ' ?';
					}
					var proceed = confirm(confirmMessage);
					if (proceed) {
						// deleting tissue
						new Ajax.Request('mainServlet', {
							method : 'POST',
							parameters : {
								appAction : 'ajaxDeleteTissue',
								chcID : tissueToDelete.chcID,
								tissueTypeID : tissueToDelete.tissueTypeID
							},
							onFailure : function(transport) {
								handleErrorResponseWindow(transport.responseText); // cf.
								// common.js
							},
							onSuccess : function(transport) {
								var nDissociatedTissues = transport.responseText;
								loadTissues();
								successWindow("The tissue " + tissueToDelete.toString()
										+ ' was successfully deleted ! ' + nDissociatedTissues
										+ ' tissue(s) were dissociated from the deleted tissue');
								loadTissues();
							}
						});
					}

				}
			});
		}
	}
}
